module ecs {
    /**
     * 处理实体及其组件之间的关联。
     */
    export class ComponentManager extends BaseSystem {
        public entityToIdentity: NumberBag;
        public typeFactory: ComponentTypeFactory;
        private _mappers: Bag<ComponentMapper<Component>> = new Bag<ComponentMapper<Component>>();

        constructor(entityContainerSize: number){
            super();
            this.entityToIdentity = new NumberBag(entityContainerSize);
            this.typeFactory = new ComponentTypeFactory(this, entityContainerSize);
        }

        protected processSystem() {}
        
        /**
         * 获取实体的复合id
         * 
         * 复合id由单个方面唯一标识。出于性能原因，每个实体都由其组合id标识。从实体中添加或删除组件将更改其组合id。
         * @param entityId 
         */
        public getIdentity(entityId: number): number{
            return this.entityToIdentity.get(entityId);
        }

        public getMapper<T extends Component>(mapper: T): ComponentMapper<T>{
            let type = this.typeFactory.getTypeFor(mapper);
            return <ComponentMapper<T>> this._mappers.get(type.getIndex());
        }

        public registerComponentType(ct: ComponentType, capacity: number){
            let index = ct.getIndex();
            let mapper = new ComponentMapper(typeof(ct), this._world);
            mapper.components.ensureCapacity(capacity);
            this._mappers.set(index, mapper);
        }

        /** 使用{@link World}状态同步新订阅。 */
        public synchronize(es: EntitySubscription){
            
        }

        public ensureCapacity(newSize: number){
            this.typeFactory.initialMapperCapacity = newSize;
            this.entityToIdentity.ensureCapacity(newSize);
            for (let m in this._mappers){
                let mapper = this._mappers[m] as ComponentMapper<Component>;
                mapper.components.ensureCapacity(newSize);
            }
        }
    }
}